package com.yayako.security.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yayako.result.Result;
import com.yayako.result.ResultFactory;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@Component
public class AuthSuccessHandler implements AuthenticationSuccessHandler {
  @Override
  public void onAuthenticationSuccess(
      HttpServletRequest req, HttpServletResponse resp, Authentication auth) throws IOException {
    resp.setContentType("application/json;charset=utf-8");
    ObjectMapper om = new ObjectMapper();
    PrintWriter out = resp.getWriter();
    String token =
        Jwts.builder()
            .claim("authentication", auth)
            .setSubject("主题")
            //                .setExpiration(new Date(System.currentTimeMillis()+60*60*24))
            .setExpiration(new Date(System.currentTimeMillis()))
            .signWith(SignatureAlgorithm.HS512, "MyJWT")
            .compact();
    //        resp.addHeader("Authenorization","Mrain"+token);
    //        Map<String, Object> tokenInfo = new HashMap<String, Object>();
    //        tokenInfo.put("Authorization",token);
    Result result = ResultFactory.bulidSuccessResult(null);
    //        result.setData(token);
    out.write(om.writeValueAsString(result));
    out.flush();
    out.close();
  }
}
